package com.example.demodatajpa.service;

import com.example.demodatajpa.dao.BookDao;
import com.example.demodatajpa.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    BookDao bookDao;

    public void addBook(Book book){bookDao.save(book);}

    public void addAllBook(List<Book> books){bookDao.saveAll(books);}

    public void deleteByIdBook(Long id){
        bookDao.deleteById(id);
    }

    public void deleteAllBook(List<Long> ids){
        bookDao.deleteAllById(ids);
    }

    public String editBook(Book book){
        String result;
        if (bookDao.existsById(book.getId())){
            bookDao.save(book);
            result="成功";
        }else result="不成功";
        return result;
    }

    public Book findIdBook(Long ids){
        return bookDao.findById(ids).orElse(null);
    }

    public List<Book> findAllByIdBook(List<Long> ids){
        return bookDao.findAllById(ids);
    }

    public List<Book> findAllBook(){
        return bookDao.findAll();
    }





    public List<Book> getBooksByAuthorStartingWith (String author){
        return bookDao.getBooksByAuthorStartingWith(author);
    }

    public List<Book> getBooksByPriceGreaterThan (Float price){
        return bookDao.getBooksByPriceGreaterThan(price);
    }

    public Book getMaxIdBook(){
        return bookDao.getMaxIdBook();
    }

    public List<Book> getBookByIdAndAuthor(String author, Long id){
        return bookDao.getBookByIdAndAuthor(author, id);
    }

    public List<Book> getBooksByIdAndName(String name, Long id){
        return bookDao.getBooksByIdAndName(name, id);
    }

    public Page<Book> getBookByPage (Pageable pageable){
        return bookDao.findAll(pageable);
    }

    public List<Book> getBookByPage(int pageNo, int size){
        Sort.TypedSort<Book> book = Sort.sort(Book.class);
        Sort sort = book.by(Book::getPrice).descending();


        Pageable pageable = PageRequest.of(pageNo, size, sort);

        Page<Book> books = bookDao.findAll(pageable);
        return books.getContent();
    }






}
